package com.insigma.business.common.config;

import com.alibaba.fastjson.JSON;
import com.insigma.framework.ResponseMessage;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LocalWebSecurityConfig {

    @Bean
    SecurityFilterChain defaultSecurityFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .csrf().disable()
                .authorizeRequests()
                .mvcMatchers("/loginWechat").permitAll()
                .anyRequest().permitAll()
//                .and().exceptionHandling().authenticationEntryPoint(new MyAuthenticationEntryPointHandler())
//                .and().addFilterBefore(new RequestTokenFilter(), UsernamePasswordAuthenticationFilter.class)
                ;
        return httpSecurity.build();
    }


    private static void csrf(HttpServletResponse response) {
        response.setHeader("content-type", "text/html;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    }


    class MyAuthenticationEntryPointHandler implements AuthenticationEntryPoint {
        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
            csrf(response);
            response.setStatus(401);
            ResponseMessage<String> authenticationDataRet = new ResponseMessage<>();
            authenticationDataRet.setStatus("401");
            authenticationDataRet.setMessage("没有登录");
            response.getWriter().write(JSON.toJSONString(authenticationDataRet));

        }
    }
}
